import React, { memo, useCallback, useEffect, useState } from 'react'
import { ArticleListWrapper } from './style'
import { getBlogArticleListAction } from '@/store/blog/actionCreators'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import ArticleItem from '../b_article_item'
import ArticlePagination from '@/components/b_pagination'

function B_Article_List(props) {
  const { userId } = props
  const [offset, setOffset] = useState(0)
  const [limit] = useState(4)
  const [currentPage, setCurrentPage] = useState(1) // 第几页
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(getBlogArticleListAction(userId, offset, limit))
  }, [dispatch, userId, offset, limit])

  const { articleList = [] } = useSelector(
    (state) => ({
      articleList: state.blogReducer.getIn(['articleList'])
    }),
    shallowEqual
  )

  const handleChange = useCallback(
    (page, pageSize) => {
      setOffset((page - 1) * limit)
      setCurrentPage(page)
    },
    [limit]
  )

  return (
    <ArticleListWrapper>
      {articleList &&
        articleList.length > 0 &&
        articleList.map((item) => {
          return (
            <ArticleItem articleItem={item} userId={userId} key={item.key} />
          )
        })}
      <ArticlePagination
        current={currentPage}
        total={Number(articleList.length > 0 && articleList[0].total)}
        defaultPageSize={limit}
        handleChange={handleChange}
      />
    </ArticleListWrapper>
  )
}

export default memo(B_Article_List)
